import { ApiDataContext } from './../domain/apiDataContext';
import { cRequest } from './../common/http/cRequest';
import { ReisHelper } from "../common/redisHelper";
import { ServiceManager } from '../common/serviceFactory/serviceManager';
import { DataRegisterService,IGYSOrder,IRedisProjectMsg } from "./dataRegisterService";

const dsSvr = ServiceManager.Current.GetService<DataRegisterService>('DataRegisterService');
export class SyncService {
    private redis: ReisHelper<any>;
    private timer;
    private redisKey = 'TestYouJianDataSyscKey1';
    constructor() {
        this.redis = new ReisHelper<any>(13, {
            host: '47.110.64.210',
            port: 6379,
            options: {
                password: "rdz1z!x1x!"
            }
        });
    }

    Start() {
        //一分钟执行一次
        this.timer = setInterval(this.Handle.bind(this), 1000 * 60 * 1);
    }

    Stop() {
        clearInterval(this.timer);
        this.timer = null;
    }

    async Handle() {
        console.log(`供应商服务系统对接，数据获取！`);
        this.Stop();
        try {
            let redisDataList: IRedisProjectMsg[] = await this.redis.get(this.redisKey);
            if (redisDataList) {
                for (let itemRedis of redisDataList) {
                    // try
                    // {
                    //     const dataSyncResult = await dsSvr.dataSync(itemRedis.ProjectId);
                    //     if(dataSyncResult && dataSyncResult.result==1)
                    //     {
                    //         let rDataModel = redisDataList.find(x => x.ProjectId == itemRedis.ProjectId);
                    //         rDataModel.isDone = true;
                    //     }
                    // }
                    // catch (error) {
                    //     console.log("x:",error);
                    // }
                    
                    let result: { data: IGYSOrder[]; } = await cRequest.Current.Get<any>(`http://filegennet5.zepride.com/YouJianDataSync/GetSupplierSignUp?ProjectId=${itemRedis.ProjectId}`);
                    const ctx = new ApiDataContext();
                    for (let item of result.data) {
                        try {
                            const dataRegister = await ctx.DataRegister.First(x => x.id == $args1, { $args1: item.YouJianProjectId });
                            if (dataRegister) {
                                for (const key in dataRegister.data.fields) {
                                    let value = dataRegister.data.fields[key];
                                    if (!value) continue;
                                    if (!Array.isArray(value)) continue;
                                    if (value.length == 0) continue;

                                    let valueItem = value[0];
                                    if (typeof valueItem != 'object') continue;
                                    const valueItemKeys = Object.keys(valueItem);
                                    const hasPackageInfo = valueItemKeys.find(x => x == 'YouJianPackageId');
                                    if (!hasPackageInfo) continue;

                                    try{
                                        valueItem = value.find(x => x.YouJianPackageId == item.YouJianPackageId);

                                        valueItem.Supplier || (valueItem.Supplier = []);
                                        const has = valueItem.Supplier.find(x => x.SupplierName == item.SupplierName && valueItem.YouJianPackageId==item.YouJianPackageId);
                                        if (!has) {
                                            valueItem.Supplier.push(item);
                                        }
                                    }
                                    catch (error) {
                                        console.log(error);
                                    }
                                }

                                await ctx.Update(dataRegister);
                            }
                       
                            let rDataModel = redisDataList.find(x => x.ProjectId == itemRedis.ProjectId);
                            rDataModel.isDone = true;
                        }
                        catch (error) {
                            console.log(error);
                        }
                    }
                }

                let redisDataListRef: IRedisProjectMsg[] = await this.redis.get(this.redisKey);
                redisDataListRef.forEach(x=>{
                   let tmpObj=redisDataList.filter(y=>y.ProjectId==x.ProjectId && y.OrganizationId==x.OrganizationId);
                   if(tmpObj && tmpObj.length>0)
                   {
                       if(tmpObj[0].isDone)
                        x.isDone=tmpObj[0].isDone;
                   }
                });

                const resultRedisList = redisDataListRef.filter(x => !x.isDone);
                await this.redis.set(this.redisKey, resultRedisList);
            }
        } catch (error) {
            console.log(error);
        }
        finally {
            this.Start();
        }
    }
}
